﻿<%@ WebHandler Language="C#" Class="MutiUploadHandler" %>

using System;
using System.Web;
using System.IO;
using ExtBusiness.Common;
using System.Web.SessionState;

public class MutiUploadHandler : IHttpHandler, IRequiresSessionState
{
    /// <summary>
    /// 读取文件流
    /// </summary>
    /// <param name="objPostFile"></param>
    /// <returns></returns>
    public byte[] readfile(HttpPostedFile objPostFile)
    {
        Stream objStream = objPostFile.InputStream;
        // 获取文件流大小
        int filesize = objPostFile.ContentLength;
        if (filesize < 1) return null;
        // 声明等长byte数组
        byte[] filebuffer = new byte[filesize];
        // 文件保存到缓存
        objStream.Read(filebuffer, 0, filesize);
        return filebuffer;
    }

    /// <summary>
    /// 读取现有的文件内容
    /// </summary>
    /// <param name="strFilePath"></param>
    /// <returns></returns>
    public byte[] readfile(string strFilePath)
    {
        FileStream objStream = File.Open(strFilePath,FileMode.Open);
        // 获取文件流大小
        long filesize = objStream.Length;
        if (filesize < 1) return null;
        // 声明等长byte数组
        byte[] filebuffer = new byte[filesize];
        // 文件保存到缓存
        objStream.Read(filebuffer,0, filebuffer.Length);
        
        return filebuffer;
    }
    
    /// <summary>
    /// 处理
    /// </summary>
    /// <param name="context"></param>
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";

        try
        {
            HttpPostedFile file = context.Request.Files["Filedata"];

            if (file != null)
            {
                //先生成临时文件（针对断点续传）
                //string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]) + "\\";
                //if (!Directory.Exists(uploadPath))
                //{
                //    Directory.CreateDirectory(uploadPath);
                //}
                //file.SaveAs(uploadPath + file.FileName);
                //SaveAs(uploadPath + file.FileName, file);

                //读取临时文件（针对断点续传）
                //byte[] arrFiles = readfile(uploadPath + file.FileName);
                byte[] arrFiles = readfile(file);

                //上传临时文件
                if (arrFiles != null)
                {
                    //修正路径及文件名
                    string strFileExt = file.FileName.Substring(file.FileName.LastIndexOf(".") + 1);
                    string strFileName = file.FileName.Substring(0, file.FileName.LastIndexOf("."));

                    //插入数据库
                    ChBusiness.Struct.FileUploadStruct _fileUploadStruct = new ChBusiness.Struct.FileUploadStruct();
                    _fileUploadStruct.KeyId = "id";
                    _fileUploadStruct.KeyIdValue = "";
                    _fileUploadStruct.TableName = "XT_SERIAL_ATTACHMENT";
                    _fileUploadStruct.FileStoreFieldName = "FILEDATA";
                    _fileUploadStruct.FileTypeFieldName = "FILETYPE";

                    _fileUploadStruct.StoreParamFieldName = "MODULE_ID";
                    _fileUploadStruct.StoreParamValue = context.Request["moudleid"];

                    //开始上传                
                    _fileUploadStruct.FileTypeFieldValue = strFileExt;
                    _fileUploadStruct.FileBytes = arrFiles;

                    _fileUploadStruct.StoreResourceFieldName = "FILENAME";
                    _fileUploadStruct.StoreResourceNameValue = strFileName;

                    _fileUploadStruct.StoreKeyFieldName = "AppDataId";
                    _fileUploadStruct.StoreKeyValue = context.Request["iid"];

                    ChBusiness.Common.UploadFileClass ufcGloab = new ChBusiness.Common.UploadFileClass();
                    int nReturn = ufcGloab.StoreUploadFile(_fileUploadStruct, ChBusiness.Struct.DataStoreType.Insert);

                    if (nReturn == 1)
                    {
                        //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                        context.Response.Write("1");
                    }
                }
                context.Response.Write("0");
            }
            else
            {
                context.Response.Write("0");
            }
        }
        catch(Exception ex)
        {
            Common.Log.LogManage.addLogErr("上传文件错误：", ex.Message);
            context.Response.Write("0");
        }
    }

    
    //断点续传保存
    private void SaveAs(string saveFilePath, HttpPostedFile file)
    {
        long lStartPos = 0;
        int startPosition = 0;
        int endPosition = 0;
        var contentRange = HttpContext.Current.Request.Headers["Content-Range"];
        //bytes 10000-19999/1157632
        if (!string.IsNullOrEmpty(contentRange))
        {
            contentRange = contentRange.Replace("bytes", "").Trim();
            contentRange = contentRange.Substring(0, contentRange.IndexOf("/"));
            string[] ranges = contentRange.Split('-');
            startPosition = int.Parse(ranges[0]);
            endPosition = int.Parse(ranges[1]);
        }
        System.IO.FileStream fs;
        if (System.IO.File.Exists(saveFilePath))
        {
            fs = System.IO.File.OpenWrite(saveFilePath);
            lStartPos = fs.Length;

        }
        else
        {
            fs = new System.IO.FileStream(saveFilePath, System.IO.FileMode.Create);
            lStartPos = 0;
        }
        if (lStartPos > endPosition)
        {
            fs.Close();
            return;
        }
        else if (lStartPos < startPosition)
        {
            lStartPos = startPosition;
        }
        else if (lStartPos > startPosition && lStartPos < endPosition)
        {
            lStartPos = startPosition;
        }
        fs.Seek(lStartPos, System.IO.SeekOrigin.Current);
        byte[] nbytes = new byte[512];
        int nReadSize = 0;
        nReadSize = file.InputStream.Read(nbytes, 0, 512);
        while (nReadSize > 0)
        {
            fs.Write(nbytes, 0, nReadSize);
            nReadSize = file.InputStream.Read(nbytes, 0, 512);
        }
        fs.Close();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}